package thread.day2;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 除了采取synchronized关键字实现的同步代码块或者同步方法
 * 线程同步的第二种方式 JUC 的 Lock
 *  ReentrantLock 是Lock的实现类
 *  需要手动调用lock() 和 unlock() 方式对共享数据的逻辑加解锁
 *
 * @author wx
 * @create 2019-11-28 18:27
 */
public class LockDemo {
    public static void main(String[] args) {
        TicketsSell w = new TicketsSell();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);


        t1.setName("windows-1");
        t2.setName("windows-2");
        t3.setName("windows-3");
        t1.start();
        t2.start();
        t3.start();

    }

}

 class TicketsSellLock implements  Runnable{



    int ticket = 100;
     ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if (ticket>0){
                    System.out.println(Thread.currentThread().getName()+":"+ticket);
                    ticket--;
                }else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}